package pri.hillchen.springboot.shiro.common.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by hillchen on 2017/10/16 0016.
 */
public class MessageDigestUtil {
    /**
     * 生成摘要
     * @param password
     * @param salt
     * @return
     */
    public static byte[] digest(String password, byte[] salt){

        try {
            MessageDigest msgDigest = MessageDigest.getInstance("SHA");
            if (salt != null && salt.length > 0){
                msgDigest.update(salt);
            }

            byte[] digest = msgDigest.digest(password.getBytes());
            return digest;
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    public static String createCredential(String password,String salt){
        return convertToHexString(digest(password,salt.getBytes()));
    }

    private static String convertToHexString(byte data[]) {
        StringBuffer strBuffer = new StringBuffer();
        for (int i = 0; i < data.length; i++) {
            strBuffer.append(Integer.toHexString(0xff & data[i]));
        }
        return strBuffer.toString();
    }

    public static void main(String[] args){
        String password1 = createCredential("hillchen0","0324wyws");
        String password2 = createCredential("hillchen0","0324wyws");
        System.out.println(password1.equals(password2));
    }
}
